<?php


namespace app\common\business;

use app\common\lib\sms\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\Exception;

class User
{
    public $userObj = null;
    public function __construct()
    {
        $this->userObj = new UserModel();
    }
    public function login($data){
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if(empty($redisCode) || $redisCode != $data['code']){
            throw new Exception("验证码不正确",-1009);
        }
        // 判断表是否有用户记录 phone_number
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);
        if(!$user){
            // 新增
            $username = "TianQi粉-".$data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config('status.mysql.table_normal'),
            ];
            try {
                $this->userObj->save($userData);
                $userId = $this->userObj->id;
            }catch(\Exception $e){
                throw new Exception("数据库内部异常");
            }
        } else {
            // 更新逻辑待完成
            $userId = $user->id;
            $username = $user->username;
            $user->update_time = date("Y-m-d H:i:s",time());
            if(!$user->save()){
                return false;
            }
        }
        // 生成Token
        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            "id" => $userId,
            "username" => $username,
        ];
        //设置了key的过期时间 用户重复的点击登录按钮会导致生成多个无用的redis值，要拦截这种操作，判断用户是不是登录状态呗（反作弊）
        $res = cache(config("redis.token_pre").$token, $redisData, Time::userLoginExpiresTime($data['type']));
        return $res ? ["token" => $token, "username" => $username] : false;
    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id){
        $user = $this->userObj->getUserById($id);
        if(!$user || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }

    /**
     * 修改用户名
     * @param $id
     * @param $data
     * @throws Exception
     */
    public function update($id, $data){
        $user = $this->getNormalUserById($id);
        if(!$user){
            throw new Exception("用户不存在");
        }
        // 检查用户名是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if($userResult && $userResult['id'] != $id){
            throw new Exception("该用户名已经存在，请重新设置");
        }
        // 修改操作
        return $this->userObj->updateById($id, $data);
    }

    public function getNormalUserByUsername($username){
        $user = $this->userObj->getUserByUsername($username);
        if(!$user || $user->status != config('status.mysql.table_normal')){
            return [];
        }
        return $user->toArray();
    }
}